/**
 * 情感分布饼图组件
 * 
 * 作用：展示舆情数据中正面、中性、负面三种情感的分布比例
 * 使用：在首页仪表盘中展示情感分布概览
 * 数据：接收包含positive、neutral、negative三个属性的对象
 * 特点：使用环形饼图，鼠标悬停时突出显示对应区域
 */

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  CanvasRenderer,
  LabelLayout
])

// 定义属性
const props = defineProps<{
  data: {
    positive: number,
    neutral: number,
    negative: number
  }
}>()

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 创建图表实例
  chart = echarts.init(chartContainer.value)
  
  // 更新图表数据
  updateChart()
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    chart?.resize()
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    series: [
      {
        name: '情感分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: props.data.positive, 
            name: '正面', 
            itemStyle: { color: '#67c23a' }
          },
          { 
            value: props.data.neutral, 
            name: '中性', 
            itemStyle: { color: '#909399' }
          },
          { 
            value: props.data.negative, 
            name: '负面', 
            itemStyle: { color: '#f56c6c' }
          }
        ]
      }
    ]
  }
  
  chart.setOption(option)
}

// 监听数据变化，更新图表
watch(() => props.data, () => {
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
})

// 组件卸载时销毁图表
const onBeforeUnmount = () => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', () => {
    chart?.resize()
  })
}
</script>

<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 280px;
}
</style> 